from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User, Group
from django.contrib.auth.forms import UserChangeForm
from django import forms

# 取消注册所有默认模型
admin.site.unregister(Group)

# 尝试取消注册可能存在的电影相关模型
try:
    from .models import Movie, Genre, Rating
    admin.site.unregister(Movie)
    admin.site.unregister(Genre)
    admin.site.unregister(Rating)
except:
    pass

# 取消注册默认的 User 管理界面
admin.site.unregister(User)

# 自定义用户表单
class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = User
        # 只保留最基本的字段
        fields = ('username', 'email')
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 移除密码字段显示
        if 'password' in self.fields:
            self.fields['password'].widget = forms.HiddenInput()

# 自定义用户管理界面
@admin.register(User)
class CustomUserAdmin(UserAdmin):
    form = CustomUserChangeForm
    
    # 简化列表显示
    list_display = ('username', 'email', 'last_login')
    list_filter = []  # 改为空列表而不是None
    search_fields = ('username', 'email')
    ordering = ('username',)
    
    # 极简编辑界面
    fieldsets = (
        (None, {'fields': ('username', 'email')}),
        ('密码修改', {'fields': ('password',),
                  'description': '<div style="padding: 10px 0;"><a href="../password/" class="button" style="background: #447e9b; padding: 10px 15px; color: white; text-decoration: none; border-radius: 4px;">修改密码</a></div>'}),
    )
    
    # 简化添加用户页面
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'email', 'password1', 'password2'),
        }),
    )
    
    # 禁用所有批量操作
    actions = None
    
    def has_delete_permission(self, request, obj=None):
        return False
    
    def has_add_permission(self, request):
        return True
        
    def has_module_permission(self, request):
        return request.user.is_superuser
        
    def get_readonly_fields(self, request, obj=None):
        # 如果是编辑现有用户，设置某些字段为只读
        if obj:
            return ('username',)
        return () 